package controllers

import (
	"encoding/json"
	"github.com/astaxie/beego"
	"strings"
	"wego/models"
	"wego/utils"
)

type LoginController struct {
	BaseController
}

func (this *LoginController) Login() {
	data := &models.LoginData{}
	_ = json.Unmarshal(this.Ctx.Input.RequestBody, data)
	username := strings.TrimSpace(data.Username)
	password := data.Password

	if len(username) == 0 || len(password) == 0 {
		this.JsonResult(0, "用户名和密码不正确", "")
	}

	password = utils.Md5(utils.Sha1(password) + beego.AppConfig.String("authkey"))
	admin, err := models.GetAdmin(username, password)
	if admin != nil && err == nil {
		token := buildToken()
		result := make(map[string]interface{})
		result["id"] = admin.Id
		result["username"] = admin.Username
		result["nickname"] = admin.Nickname
		err := utils.SetCache(token, &result, 7200)
		if err == nil {
			result["token"] = token
			if admin.Id == 1 {
				access, _ := models.AuthAll() //超管所有权限
				result["access"] = access
			} else {
				//查询管理员权限组ID 获取权限组所有权限
				if groupId := models.GetGroupId(admin.Id); groupId != "[]" {
					access, _ := models.GetAuthByLogin(groupId)
					result["access"] = access
				} else {
					this.JsonResult(0, "此用户未分配权限", "")
				}
			}
			this.JsonResult(1, "登陆成功", &result)
		} else {
			this.JsonResult(0, "未配置Redis", "")
		}
	} else {
		this.JsonResult(0, "用户名或者密码错误", "")
	}
}

func (this *LoginController) Logout() {
	token := this.Ctx.Input.Header("Authorization")
	_ = utils.DelCache(token)
	this.JsonResult(1, "退出成功", "")
}

func buildToken() string {
	result := make(map[string]interface{})
	token := utils.RandomString(32)
	err := utils.GetCache(token, &result)
	//err 为空 存在token
	if err == nil {
		buildToken()
	}
	return token
}
